﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using Top.Api.Request;
using Top.Api.Response;
using System.Web.Security;
using Top.Api;

namespace AscentExplorer.Controllers
{
    public class TaobaoController : Controller
    {
        const string serverUrl = "http://gw.api.taobao.com/router/rest";
        const string appKey = "12344956";
        const string appSecret = "3865429228e6ffd6fb132510ed91c2d7";

        [Authorize(Roles = "TaobaoUsers")]
        public ActionResult Index(string code, string state)
        {
            MembershipUser user = Membership.GetUser(User.Identity.Name);
            string userNick = Convert.ToString(Session["taobaoUserNick"]);
            string sessionKey = Convert.ToString(Session["taobaoSessionKey"]);

            //TaobaoServiceReference.TaobaoServiceClient client = new TaobaoServiceReference.TaobaoServiceClient("NetNamedPipeBinding_ITaobaoService");
            //client.Start(userNick, sessionKey);

            return View();
        }

        public RedirectResult Authorize()
        {
            const string authorize_url = "https://oauth.taobao.com/authorize";
            const string response_type = "code";
            const string redirect_uri = "http://127.0.0.1/taobao/token";
            string state = string.Empty;

            string url = string.Format("{0}?response_type={1}&client_id={2}&redirect_uri={3}&state={4}", authorize_url, response_type, appKey, redirect_uri, state);
            return Redirect(url);
        }

        public RedirectToRouteResult Token(string code, string state)
        {
            const string grant_type = "authorization_code";
            //string code;
            const string redirect_uri = "http://127.0.0.1/taobao";
            string queryString = string.Format("grant_type={0}&code={1}&redirect_uri={2}&client_id={3}&client_secret={4}", grant_type, code, redirect_uri, appKey, appSecret);

            string accessToken;
            using (HttpClient client = new HttpClient("https://oauth.taobao.com/"))
            {
                string requestUri = "token?" + queryString;
                accessToken = client.Post(requestUri, null).Content.ReadAsString();
                string sessionKey = accessToken.Split(',')[2].Split(':')[1].Replace("\"", "").Replace("}", "").Trim();
                UserGetRequest request = new UserGetRequest() { Fields = "user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind" };
                UserGetResponse response = DoExecute(request, sessionKey, DateTime.Now);
                //如果当前登录用户不在我们系统，就建立用户----并且将一些特殊信息写到 comment 中
                MembershipUser user = Membership.GetUser(response.User.Email);
                if (null == user)
                {
                    user = Membership.CreateUser(response.User.Email, new Guid().ToString(), response.User.Email);
                    Roles.AddUserToRole(response.User.Email, "TaobaoUsers");
                }
                user.Comment = string.Format("taobao:{0}:{1}", response.User.Nick, sessionKey);
                Membership.UpdateUser(user);

                Session["taobaoUserNick"] = response.User.Nick;
                Session["taobaoSessionKey"] = sessionKey;
                FormsAuthentication.SetAuthCookie(response.User.Email, true);
            }
            
            return RedirectToAction("Index", "Taobao");
        }

        private static T DoExecute<T>(ITopRequest<T> request, string session, DateTime timestamp) where T : TopResponse
        {
            ITopClient client = new DefaultTopClient(serverUrl, appKey, appSecret);
            return client.Execute(request, session, timestamp);
        }

    }
}
